package com.gxnu.edu.cn.ttxxt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Optional;

@Mapper
public interface NotificationRepository extends BaseMapper<Notifications> {

    @Select("SELECT * FROM notifications WHERE receiver_id = #{receiverId} and status=3 ORDER BY create_time DESC")
    List<Notifications> findByReceiverId(@Param("receiverId") Long receiverId);

    @Select("SELECT * FROM notifications WHERE receiver_id = #{receiverId} AND  (type = 1 OR type = 4 or type=5) and  (status = 1 OR status = 2) ORDER BY create_time DESC")
    List<Notifications> findByReceiverIdAndStatus(@Param("receiverId") Long receiverId,
                                                  @Param("status") Integer status);

    @Select("SELECT * FROM notifications WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} AND type = #{type} LIMIT 1")
    Optional<Notifications> findBySenderIdAndReceiverIdAndType(@Param("senderId") Long senderId,
                                                               @Param("receiverId") Long receiverId,
                                                               @Param("type") Integer type);

    @Select("SELECT COUNT(*) > 0 FROM notifications WHERE sender_id = #{senderId} AND receiver_id = #{receiverId} AND type = #{type}")
    boolean existsBySenderIdAndReceiverIdAndType(@Param("senderId") Long senderId,
                                                 @Param("receiverId") Long receiverId,
                                                 @Param("type") Integer type);

    @Update("UPDATE notifications SET status = #{newStatus} WHERE receiver_id = #{userId} AND status = #{oldStatus}")
    void updateStatusByReceiverId(@Param("userId") Long userId,
                                  @Param("oldStatus") Integer oldStatus,
                                  @Param("newStatus") Integer newStatus);

    @Update("UPDATE notifications SET status = #{notification.status}, process_time = #{notification.processTime} " +
            "WHERE notification_id = #{notification.notificationId}")
    void update(@Param("notification") Notifications notifications);

    @Select("SELECT * FROM notifications WHERE notification_id=#{notificationId}")
    Notifications selectById1(Long notificationId);

    @Update("UPDATE notifications SET status =3, type = 2 " +
            "WHERE notification_id = #{notifications}")
    void updateById1(Long notifications);
}
